{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "dimension = 400\n",
    "vocab = \"EOS abcdefghijklmnopqrstuvwxyz'\"\n",
    "char2idx = {char: idx for idx, char in enumerate(vocab)}\n",
    "idx2char = {idx: char for idx, char in enumerate(vocab)}\n",
    "\n",
    "def text2idx(text):\n",
    "    text = re.sub(r'[^a-z ]', '', text.lower()).strip()\n",
    "    converted = [char2idx[char] for char in text]\n",
    "    return text, converted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = 1\n",
    "PAD = 0\n",
    "EOS = 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "\n",
    "train_X, train_Y = [], []\n",
    "text_files = [f for f in os.listdir('spectrogram-train') if f.endswith('.npy')]\n",
    "for fpath in text_files:\n",
    "    try:\n",
    "        splitted = fpath.split('-')\n",
    "        if len(splitted) == 2:\n",
    "            splitted[1] = splitted[1].split('.')[1]\n",
    "            fpath = splitted[0] + '.' + splitted[1]\n",
    "        with open('data/' + fpath.replace('npy', 'txt')) as fopen:\n",
    "            text, converted = text2idx(fopen.read())\n",
    "        w = np.load('spectrogram-train/' + fpath)\n",
    "        if w.shape[1] != dimension:\n",
    "            continue\n",
    "        train_X.append(w)\n",
    "        train_Y.append(converted)\n",
    "    except:\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_X, test_Y = [], []\n",
    "text_files = [f for f in os.listdir('spectrogram-test') if f.endswith('.npy')]\n",
    "for fpath in text_files:\n",
    "    with open('data/' + fpath.replace('npy', 'txt')) as fopen:\n",
    "        text, converted = text2idx(fopen.read())\n",
    "    w = np.load('spectrogram-test/' + fpath)\n",
    "    if w.shape[1] != dimension:\n",
    "        continue\n",
    "    test_X.append(w)\n",
    "    test_Y.append(converted)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "def encoder_block(inp, n_hidden, filter_size):\n",
    "    inp = tf.expand_dims(inp, 2)\n",
    "    inp = tf.pad(inp, [[0, 0], [(filter_size[0]-1)//2, (filter_size[0]-1)//2], [0, 0], [0, 0]])\n",
    "    conv = tf.layers.conv2d(inp, n_hidden, filter_size, padding=\"VALID\", activation=None)\n",
    "    conv = tf.squeeze(conv, 2)\n",
    "    return conv\n",
    "\n",
    "def glu(x):\n",
    "    return tf.multiply(x[:, :, :tf.shape(x)[2]//2], tf.sigmoid(x[:, :, tf.shape(x)[2]//2:]))\n",
    "\n",
    "def layer(inp, conv_block, kernel_width, n_hidden, residual=None):\n",
    "    z = conv_block(inp, n_hidden, (kernel_width, 1))\n",
    "    return glu(z) + (residual if residual is not None else 0)\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[0]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Model:\n",
    "    def __init__(\n",
    "        self,\n",
    "        num_layers,\n",
    "        size_layers,\n",
    "        learning_rate,\n",
    "        num_features,\n",
    "        dropout = 1.0,\n",
    "    ):\n",
    "        self.X = tf.placeholder(tf.float32, [None, None, num_features])\n",
    "        self.label = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y_seq_len = tf.placeholder(tf.int32, [None])\n",
    "        self.Y = tf.sparse_placeholder(tf.int32)\n",
    "        seq_lens = tf.count_nonzero(\n",
    "            tf.reduce_sum(self.X, -1), 1, dtype = tf.int32\n",
    "        )\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        def cells(reuse = False):\n",
    "            return tf.contrib.rnn.DropoutWrapper(\n",
    "                tf.nn.rnn_cell.LSTMCell(\n",
    "                    size_layers,\n",
    "                    initializer = tf.orthogonal_initializer(),\n",
    "                    reuse = reuse,\n",
    "                ),\n",
    "                state_keep_prob = dropout,\n",
    "                output_keep_prob = dropout,\n",
    "            )\n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layers, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layers)\n",
    "        \n",
    "        encoder_embedded = self.X\n",
    "        encoder_embedded = tf.layers.conv1d(encoder_embedded, size_layers, 1)\n",
    "        e = tf.identity(encoder_embedded)\n",
    "        for i in range(num_layers * 2):\n",
    "            z = layer(encoder_embedded, encoder_block, 3, size_layers * 2, encoder_embedded)\n",
    "            encoder_embedded = z\n",
    "        \n",
    "        encoder_output, output_memory = z, z + e\n",
    "        print(encoder_output, output_memory)\n",
    "        \n",
    "        init_state = tf.reduce_mean(output_memory,axis=1)\n",
    "        encoder_state = tuple(tf.nn.rnn_cell.LSTMStateTuple(c=init_state, h=init_state) for _ in range(num_layers))\n",
    "        main = tf.strided_slice(self.X, [0, 0, 0], [batch_size, -1, num_features], [1, 1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1, num_features], 0.0), main], 1)\n",
    "        decoder_cell = attention(encoder_output, seq_lens)\n",
    "        dense_layer = tf.layers.Dense(len(vocab))\n",
    "        \n",
    "        training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                inputs = decoder_input,\n",
    "                sequence_length = seq_lens,\n",
    "                time_major = False)\n",
    "        training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                cell = decoder_cell,\n",
    "                helper = training_helper,\n",
    "                initial_state = decoder_cell.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state),\n",
    "                output_layer = dense_layer)\n",
    "        training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = training_decoder,\n",
    "                impute_finished = True,\n",
    "                maximum_iterations = tf.reduce_max(seq_lens))\n",
    "        self.seq_lens = seq_lens\n",
    "        \n",
    "        logits = training_decoder_output.rnn_output\n",
    "        time_major = tf.transpose(logits, [1, 0, 2])\n",
    "        self.time_major = time_major\n",
    "        decoded, log_prob = tf.nn.ctc_beam_search_decoder(time_major, seq_lens)\n",
    "        decoded = tf.to_int32(decoded[0])\n",
    "        self.preds = tf.sparse.to_dense(decoded)\n",
    "        self.cost = tf.reduce_mean(\n",
    "            tf.nn.ctc_loss(\n",
    "                self.Y,\n",
    "                time_major,\n",
    "                seq_lens\n",
    "            )\n",
    "        )\n",
    "        self.optimizer = tf.train.AdamOptimizer(\n",
    "            learning_rate = learning_rate\n",
    "        ).minimize(self.cost)\n",
    "        \n",
    "        preds = self.preds[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        preds = pad_second_dim(preds, tf.reduce_max(self.Y_seq_len))\n",
    "        y_t = tf.cast(preds, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.label, masks)\n",
    "        self.mask_label = mask_label\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING: Logging before flag parsing goes to stderr.\n",
      "W0830 22:01:10.105256 140353921439552 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "W0830 22:01:10.115298 140353921439552 deprecation.py:323] From <ipython-input-6-bf2828824d5e>:57: conv1d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.keras.layers.Conv1D` instead.\n",
      "W0830 22:01:10.120007 140353921439552 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "W0830 22:01:10.239052 140353921439552 deprecation.py:323] From <ipython-input-6-bf2828824d5e>:4: conv2d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.keras.layers.Conv2D` instead.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tensor(\"add_3:0\", shape=(?, ?, 512), dtype=float32) Tensor(\"add_4:0\", shape=(?, ?, 512), dtype=float32)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "W0830 22:01:11.372579 140353921439552 lazy_loader.py:50] \n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "W0830 22:01:11.675654 140353921439552 deprecation.py:323] From <ipython-input-6-bf2828824d5e>:42: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "W0830 22:01:11.681477 140353921439552 deprecation.py:323] From <ipython-input-6-bf2828824d5e>:52: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "W0830 22:01:12.654093 140353921439552 deprecation.py:506] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "W0830 22:01:13.462634 140353921439552 deprecation.py:323] From /home/husein/.local/lib/python3.6/site-packages/tensorflow/contrib/seq2seq/python/ops/attention_wrapper.py:2078: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "W0830 22:01:13.576039 140353921439552 deprecation.py:323] From <ipython-input-6-bf2828824d5e>:92: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "\n",
    "size_layers = 512\n",
    "learning_rate = 1e-4\n",
    "num_layers = 2\n",
    "batch_size = 64\n",
    "epoch = 20\n",
    "\n",
    "model = Model(num_layers, size_layers, learning_rate, dimension)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = tf.keras.preprocessing.sequence.pad_sequences(\n",
    "    train_X, dtype = 'float32', padding = 'post'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_X = tf.keras.preprocessing.sequence.pad_sequences(\n",
    "    test_X, dtype = 'float32', padding = 'post'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens\n",
    "\n",
    "def sparse_tuple_from(sequences, dtype=np.int32):\n",
    "    indices = []\n",
    "    values = []\n",
    "\n",
    "    for n, seq in enumerate(sequences):\n",
    "        indices.extend(zip([n] * len(seq), range(len(seq))))\n",
    "        values.extend(seq)\n",
    "\n",
    "    indices = np.asarray(indices, dtype=np.int64)\n",
    "    values = np.asarray(values, dtype=dtype)\n",
    "    shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64)\n",
    "\n",
    "    return indices, values, shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:28<00:00,  1.79it/s, accuracy=0.784, cost=12]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.45it/s, accuracy=0.773, cost=13.4]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg cost 22.843679, training avg accuracy 0.551524\n",
      "epoch 1, testing avg cost 13.325702, testing avg accuracy 0.772444\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:26<00:00,  1.80it/s, accuracy=0.784, cost=11.2]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.52it/s, accuracy=0.777, cost=11.8]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg cost 11.787023, training avg accuracy 0.776832\n",
      "epoch 2, testing avg cost 11.816154, testing avg accuracy 0.779041\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:27<00:00,  1.73it/s, accuracy=0.806, cost=9.78]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.46it/s, accuracy=0.771, cost=11.3]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg cost 10.717728, training avg accuracy 0.787439\n",
      "epoch 3, testing avg cost 11.396130, testing avg accuracy 0.776252\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:32<00:00,  1.73it/s, accuracy=0.82, cost=8.86] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.49it/s, accuracy=0.775, cost=11.7]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg cost 9.914606, training avg accuracy 0.799418\n",
      "epoch 4, testing avg cost 11.572537, testing avg accuracy 0.781861\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:33<00:00,  1.75it/s, accuracy=0.82, cost=8.25] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.51it/s, accuracy=0.773, cost=12.1]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg cost 9.083913, training avg accuracy 0.812834\n",
      "epoch 5, testing avg cost 11.790721, testing avg accuracy 0.781523\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:28<00:00,  1.78it/s, accuracy=0.863, cost=7.26]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.51it/s, accuracy=0.773, cost=12.2]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg cost 8.280313, training avg accuracy 0.828048\n",
      "epoch 6, testing avg cost 12.523357, testing avg accuracy 0.786584\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:29<00:00,  1.75it/s, accuracy=0.827, cost=6.91]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.51it/s, accuracy=0.772, cost=12.2]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg cost 7.425717, training avg accuracy 0.842378\n",
      "epoch 7, testing avg cost inf, testing avg accuracy 0.787262\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:32<00:00,  1.72it/s, accuracy=0.892, cost=6.41]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.49it/s, accuracy=0.779, cost=12.3]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg cost 6.640522, training avg accuracy 0.857383\n",
      "epoch 8, testing avg cost 13.313684, testing avg accuracy 0.791818\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:31<00:00,  1.73it/s, accuracy=0.906, cost=5.14]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.44it/s, accuracy=0.787, cost=12.7]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg cost 5.950582, training avg accuracy 0.869927\n",
      "epoch 9, testing avg cost 13.820772, testing avg accuracy 0.792435\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:34<00:00,  1.72it/s, accuracy=0.871, cost=5.63]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.47it/s, accuracy=0.775, cost=14.4]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg cost 5.191116, training avg accuracy 0.884032\n",
      "epoch 10, testing avg cost 14.773592, testing avg accuracy 0.791521\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:35<00:00,  1.74it/s, accuracy=0.921, cost=4.37]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.49it/s, accuracy=0.793, cost=14.7]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg cost 4.592854, training avg accuracy 0.894829\n",
      "epoch 11, testing avg cost inf, testing avg accuracy 0.792228\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:36<00:00,  1.66it/s, accuracy=0.914, cost=4.35]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.45it/s, accuracy=0.786, cost=16.2]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg cost 4.044317, training avg accuracy 0.905290\n",
      "epoch 12, testing avg cost 16.948906, testing avg accuracy 0.792237\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:37<00:00,  1.65it/s, accuracy=0.921, cost=3.74]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.43it/s, accuracy=0.792, cost=16.8]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg cost 3.496344, training avg accuracy 0.916858\n",
      "epoch 13, testing avg cost 17.670719, testing avg accuracy 0.792578\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:39<00:00,  1.64it/s, accuracy=0.935, cost=3.06]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.40it/s, accuracy=0.796, cost=18.4]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg cost 3.089757, training avg accuracy 0.924015\n",
      "epoch 14, testing avg cost 18.522146, testing avg accuracy 0.799595\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:41<00:00,  1.63it/s, accuracy=0.935, cost=2.92]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.42it/s, accuracy=0.785, cost=18.8]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg cost 2.671993, training avg accuracy 0.932817\n",
      "epoch 15, testing avg cost 19.291397, testing avg accuracy 0.799696\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:43<00:00,  1.62it/s, accuracy=0.942, cost=2.44]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.41it/s, accuracy=0.792, cost=20.6]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg cost 2.382796, training avg accuracy 0.938367\n",
      "epoch 16, testing avg cost 19.683201, testing avg accuracy 0.798279\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:43<00:00,  1.62it/s, accuracy=0.95, cost=2.18] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.38it/s, accuracy=0.786, cost=22.3]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg cost 2.003694, training avg accuracy 0.947037\n",
      "epoch 17, testing avg cost 21.430529, testing avg accuracy 0.798072\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:43<00:00,  1.61it/s, accuracy=0.942, cost=2.02]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.41it/s, accuracy=0.802, cost=21.9]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg cost 1.906986, training avg accuracy 0.948546\n",
      "epoch 18, testing avg cost 21.528790, testing avg accuracy 0.801692\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:44<00:00,  1.63it/s, accuracy=0.942, cost=1.6]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.38it/s, accuracy=0.779, cost=23.1]\n",
      "minibatch loop:   0%|          | 0/206 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg cost 1.680656, training avg accuracy 0.953059\n",
      "epoch 19, testing avg cost 24.193068, testing avg accuracy 0.801057\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 206/206 [02:44<00:00,  1.63it/s, accuracy=0.935, cost=1.98] \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:06<00:00,  1.40it/s, accuracy=0.802, cost=26.1]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg cost 1.497375, training avg accuracy 0.957022\n",
      "epoch 20, testing avg cost 25.008738, testing avg accuracy 0.802387\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_cost, train_accuracy, test_cost, test_accuracy = [], [], [], []\n",
    "    for i in pbar:\n",
    "        batch_x = train_X[i : min(i + batch_size, len(train_X))]\n",
    "        y = train_Y[i : min(i + batch_size, len(train_X))]\n",
    "        batch_y = sparse_tuple_from(y)\n",
    "        batch_label, batch_len = pad_sentence_batch(y, 0)\n",
    "        _, cost, accuracy = sess.run(\n",
    "            [model.optimizer, model.cost, model.accuracy],\n",
    "            feed_dict = {model.X: batch_x, model.Y: batch_y, \n",
    "                         model.label: batch_label, model.Y_seq_len: batch_len},\n",
    "        )\n",
    "        train_cost.append(cost)\n",
    "        train_accuracy.append(accuracy)\n",
    "        pbar.set_postfix(cost = cost, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'testing minibatch loop')\n",
    "    for i in pbar:\n",
    "        batch_x = test_X[i : min(i + batch_size, len(test_X))]\n",
    "        y = test_Y[i : min(i + batch_size, len(test_X))]\n",
    "        batch_y = sparse_tuple_from(y)\n",
    "        batch_label, batch_len = pad_sentence_batch(y, 0)\n",
    "        cost, accuracy = sess.run(\n",
    "            [model.cost, model.accuracy],\n",
    "            feed_dict = {model.X: batch_x, model.Y: batch_y, \n",
    "                         model.label: batch_label, model.Y_seq_len: batch_len},\n",
    "        )\n",
    "        \n",
    "        test_cost.append(cost)\n",
    "        test_accuracy.append(accuracy)\n",
    "        \n",
    "        pbar.set_postfix(cost = cost, accuracy = accuracy)\n",
    "    print('epoch %d, training avg cost %f, training avg accuracy %f'%(e + 1, np.mean(train_cost), \n",
    "                                                                      np.mean(train_accuracy)))\n",
    "    \n",
    "    print('epoch %d, testing avg cost %f, testing avg accuracy %f'%(e + 1, np.mean(test_cost), \n",
    "                                                                    np.mean(test_accuracy)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "real: say the word bath\n",
      "predicted: say the word chash\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "random_index = random.randint(0, len(test_X) - 1)\n",
    "batch_x = test_X[random_index : random_index + 1]\n",
    "print(\n",
    "    'real:',\n",
    "    ''.join(\n",
    "        [idx2char[no] for no in test_Y[random_index : random_index + 1][0]]\n",
    "    ),\n",
    ")\n",
    "batch_y = sparse_tuple_from(test_Y[random_index : random_index + 1])\n",
    "pred = sess.run(model.preds, feed_dict = {model.X: batch_x})[0]\n",
    "print('predicted:', ''.join([idx2char[no] for no in pred]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
